package task

import (
	"fmt"
	"time"

	"gitee.com/kobeyyf/mkm/service/model"
	"xorm.io/xorm"
)

// 任务调度器,
// 用于多任务调度, 启动, 终止
type TaskMgr struct {
	engine *xorm.Engine
	task   *Task
}

func NewTaskMgr(engine *xorm.Engine) (*TaskMgr, error) {

	tm := &TaskMgr{
		engine: engine,
	}
	err := tm.loadTask()

	return tm, err
}

func (tm *TaskMgr) run() {
	for {

		if tm.task == nil || tm.task.IsDone() {
			// 更新任务信息
			if tm.UpdateTaskLog(); err != nil {
				fmt.Println("update Task log faield ", err)
			}

			if err := tm.loadTask(); err != nil {
				fmt.Println("load task faield", err)
			}
		}

		time.Sleep(time.Minute)
	}
}

func (tm *TaskMgr) UpdateTaskLog() error {

}

func (tm *TaskMgr) loadTask() error {
	task := new(model.Task)
	has, err := tm.engine.Where("status=?", model.STATUS_UNDO).Asc("appointment_time").Get(task)
	if err != nil {
		return err
	}
	if !has {
		return nil
	}

	if task.AppointmentTime > time.Now().Unix() {
		return nil
	}

	devices := make([]*model.Device, 0, 100)
	if err = tm.engine.Where("device_group_id=?", task.DeviceGroupId).Find(&devices); err != nil {
		return err
	}
	products := make([]*model.LogProduct, 0, 100)
	if err = tm.engine.Where("task_id=?", task.TaskId).Find(&products); err != nil {
		return err
	}

	// 更新状态
	task.StartTime = time.Now().Unix()
	task.DeviceCount = len(devices)
	task.Status = model.STATUS_DOING
	task.ProductCount = len(products)
	if _, err = tm.engine.Where("task_id=?", task.TaskId).Cols("status", "start_time", "product_count", "device_count").Update(task); err != nil {
		return err
	}
	tm.task = NewTask(task, devices, products)

	return nil
}

func (tm *TaskMgr) Next(deviceId uint32) *model.LogProduct {
	if tm.task != nil {
		p := tm.task.Next(deviceId)
		if p != nil {
			return p
		}
	}
	time.Sleep(time.Second * 30)
	return &model.LogProduct{}

}
